﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;
using AG.Utilities;


namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class ServiceCheckMaintenancePlanWithRebuildIndex : IssueTypeCheckBase
    {

        public ServiceCheckMaintenancePlanWithRebuildIndex()
        {
            IssueTypeId = 2012;
        }

        public override void Check()
        {
            try
            {
                
                HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);


                // Query for maintenance plans with rebuild index task

                var Qry = from m in dc.MaintenanceSubPlans
                                     where m.HasReBuildIndexTask == true
                                     select m;

                IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                foreach (var maintenancePlan in Qry.GroupBy(m => m.MaintenancePlan).Select(g => g.First()))
                {

                    //Create new Issue

                    Issue issue = new Issue();
                    issue.IssueType = issueType;
                    issue.TargetId = maintenancePlan.ServiceId;
                    issue.Description = issueType.Description.Replace("{MaintenancePlan}", maintenancePlan.MaintenancePlan);

                    dc.Issues.InsertOnSubmit(issue);
                }

                dc.SubmitChanges();

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

    }
}
